package com.zjj.controller;


import com.github.pagehelper.PageInfo;
import com.zjj.entity.Employee;
import com.zjj.entity.R;
import com.zjj.enums.HttpEnum;
import com.zjj.service.EmployeeService;
import com.zjj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/emps")
@CrossOrigin
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    //获取全部书籍
    @GetMapping
    public PageInfo<Employee> getList(String empName, String jobTitle, Integer pageNum) {
        PageInfo<Employee> workerList = employeeService.getList(empName, jobTitle, pageNum);
        return R.success(workerList).getData();
    }

    @GetMapping("/page")
    public R<Object> getPage(String empName, String jobTitle, Integer pageNum) {
        PageInfo<Employee> workerPageInfo = employeeService.getPage(empName,jobTitle,pageNum);
        return R.success(pageNum);
    }
    //获取书籍详情
    @GetMapping("{id}")
    public R<Employee> getWorkerInfo(@PathVariable("id") Integer employeeId) {
        return R.success(employeeService.saveEmployee(employeeId));
    }
    //新增书籍
    @PostMapping
    public R saveEmployee(@Valid Employee employee, MultipartFile imagepath, HttpServletRequest request) {
        //todo 默认设置书籍类型为1
        employee.setEmployee_id(1);
        // 得到上传图片的地址
        String imgPath;
        try {
            //ImageUtil为之前添加的工具类
            imgPath = FileUtil.upload(request, imagepath);
            if (imgPath != null) {
                // 将上传图片的地址封装到实体类
                employee.setImage_path(imgPath);
                System.out.println("-----------------图片上传成功！");
            } else {
                System.out.println("-----------------图片上传失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("----------------图片上传失败！");
        }
        int count = employeeService.saveEmployee(employee);

        return count > 0 ? R.success("书籍新增成功") : R.fail(HttpEnum.ERROR.getCode(),"书籍新增失败");
    }
}
